package com.rey.demo.link;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

/**
 * @ClassName: ZookeeperDemo
 * @Description: TODO
 * @Author reyJojo
 * @Date 2021/12/2 19:23
 * @Version 1.0
 */
public class ZookeeperDemo {
    public static void main(String[] args) {
        try{
            final CountDownLatch countDownLatch=new CountDownLatch(1);
            ZooKeeper zooKeeper= new ZooKeeper("39.104.13.176:2181",
                            4000, (event)->{
                        if(Watcher.Event.KeeperState.SyncConnected==event.getState()){
                            //如果收到了服务端的响应事件，连接成功
                            countDownLatch.countDown();
                        }
                    });
            countDownLatch.await();
            //CONNECTED
            System.out.println(zooKeeper.getState());

        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }
    public static ZooKeeper link4ZookeeperApi(){
        try{
            final CountDownLatch countDownLatch=new CountDownLatch(1);
            ZooKeeper zooKeeper= new ZooKeeper("39.104.13.176:2181",
                    4000, (event)->{
                if(Watcher.Event.KeeperState.SyncConnected==event.getState()){
                    //如果收到了服务端的响应事件，连接成功
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
            //CONNECTED
            System.out.println(zooKeeper.getState());
            return zooKeeper;

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
